package com.unbox.common.aspect;

import com.unbox.common.annotation.AnnotationAbstractFactory;
import com.unbox.common.configuration.exception.UnboxAnnotionException;
import com.unbox.common.util.UnBoxUtils;
import com.unbox.common.util.UnboxLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;

/**
 * 定义切面拦截控制器进行接口参数验证
 */
@Aspect
@Import(AnnotationAbstractFactory.class)
public class UnboxAnnotationAspet {
    /**
     * 国际化日志输出
     */
    UnboxLog log = new UnBoxUtils.LocaleMessageLog(UnboxAnnotationAspet.class);

    public UnboxAnnotationAspet(){
        log.info("validation.info.aop.msg");
    }

    @Autowired(required = false)
    UnboxAnnotationHander unboxAnnotationAdapter;

    @Autowired
    AnnotationAbstractFactory annotationAbstractFactory;

    // 定义一个切入点
    @Pointcut("@annotation(com.unbox.common.annotation.Validated)")
    private void cut(){}

    /**
     *  功能:前置通知
     */
    @Before("cut()")
    public void before(JoinPoint point) {
        if (unboxAnnotationAdapter != null) { unboxAnnotationAdapter.before(point); return;};
        try {
            annotationAbstractFactory.validated(point.getTarget(), point.getSignature().getName(), point.getArgs());
        } catch (Exception e) {
            throw new UnboxAnnotionException(e.getMessage());
        }
    }
}
